using System;
using System.Collections.Generic;
using System.Text;
using agsXMPP;
using agsXMPP.protocol.client;

namespace PoshXmpp
{
    public class MessageManager
    {
        Queue<Message> _messages = new Queue<Message>();

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="client">The <see cref="XmppClientConnection"/></param>
        public MessageManager(XmppClient client)
        {
            client.OnMessage += new agsXMPP.protocol.client.MessageHandler(OnClientMessageReceived);
        }

        /// <summary>
        /// Event handler for the <see cref="agsXMPP.XmppClientConnection.OnMessage"/> event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="msg"></param>
        void OnClientMessageReceived(object sender, Message msg)
        {
            _messages.Enqueue(msg);
        }

        /// <summary>
        /// Retrieve the single "next" message in the queue
        /// </summary>
        public Message NextMessage
        {
            get
            {
                if (HasMessages)
                {
                    return _messages.Dequeue();
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// True if there are messages in the queue, False otherwise
        /// </summary>
        public bool HasMessages
        {
            get
            {
                return _messages.Count > 0;
            }
        }

        /// <summary>
        /// Enumerator for messages in the queue
        /// </summary>
        public IEnumerable<Message> Messages
        {
            get
            {
                while (HasMessages) yield return _messages.Dequeue();
            }
        }
    }
}